#include "image.h"
#include "color.h"

void
flip_init_image(flip_image_data* self, unsigned width, unsigned height, uint32_t format)
{
	size_t size;
		
	self->cached.pixels = 0;
	self->cached.width = width;
	self->cached.height = height;
	self->cached.format = format;
	
	self->pf = *flip_unpack_pf(format);
	
	size = width * height * self->pf.bytespp;
	self->cached.pixels = malloc(size);
	memset(self->cached.pixels, 0, size);
}

void
flip_uninit_image(flip_image_data* self)
{
	free(self->cached.pixels);
}

void
flip_init_image_copy_data(
	flip_image_data* self,
	unsigned width,
	unsigned height,
	uint32_t format,
	void const* data)
{
	flip_init_image(self, width, height, format);
	memcpy(self->cached.pixels, data, width * height * self->pf.bytespp);
}

void
flip_init_image_take_data(
	flip_image_data* self,
	unsigned width,
	unsigned height,
	uint32_t format,
	void* data)
{

	self->cached.pixels = 0;
	self->cached.width = width;
	self->cached.height = height;
	self->cached.format = format;
	
	self->pf = *flip_unpack_pf(format);
	
	self->cached.pixels = data;
}

void
flip_image_draw(flip_image_data* src, flip_image_data* dest, unsigned int x, unsigned int y)
{
	if(src->cached.format == dest->cached.format)
	{
		unsigned px, py;
		unsigned srcw = src->cached.width;
		unsigned srch = src->cached.height;
		for(py = 0; py < srch; ++py)
		for(px = 0; px < srcw; ++px)
		{
			flip_set_pixel(dest, px + x, py + y, flip_get_pixel(src, px, py));
		}
	}
}